import telepot
import os
from requests import get
from bs4 import BeautifulSoup as bsoup
from os.path import join, exists
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton

def get_link():
    url = "https://www.smbc-comics.com"
    r = get(url)
    s = bsoup(r.text, 'lxml')
    html = s.select("#cc-comicbody > img")[0]
    permalink = s.select("#permalink > #permalinktext")[0]['value']
    title, link = html['title'], html['src']
    return title, link, permalink

def k(url):
    emoji = u'\U0001F517' # Unicode per emoji dell'hyperlink
    return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text=emoji, url=url)],])    

def check_db(new):
   cwd = os.getcwd()
   if not exists('last-smbc.txt'):
       with open('last-smbc.txt', 'w') as reg:
           reg.write(new)
           return True
       with open('last-smbc.txt', 'r') as reg:
           old = readline()
           if old != new:
               with open('last-smbc.txt', 'w') as reg:
                   reg.write(new)
                   return True
       return False

def smbc():
    chat_id = -1001041086151
    caption, link, permalink = get_link()
    if check_db(link):
        bot.sendPhoto(chat_id, link, caption=caption, reply_markup=k(permalink))


with open('auth', 'r') as a:
    token = a.readlines().strip()

bot = telepot.Bot(token)
smbc()
